package com.liang.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liang.shortlink.admin.common.biz.user.UserContext;
import com.liang.shortlink.admin.common.constants.RedisCacheConstant;
import com.liang.shortlink.admin.common.convention.exception.ClientException;
import com.liang.shortlink.admin.common.convention.result.Result;
import com.liang.shortlink.admin.dao.entity.GroupDO;
import com.liang.shortlink.admin.dao.mapper.GroupMapper;
import com.liang.shortlink.admin.dto.req.ShortLinkGroupSortReqDTO;
import com.liang.shortlink.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import com.liang.shortlink.admin.dto.resp.ShortLinkGroupRespDTO;
import com.liang.shortlink.admin.remote.ShortLinkClient;
import com.liang.shortlink.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDTO;
import com.liang.shortlink.admin.service.GroupService;
import com.liang.shortlink.admin.toolkit.RandomGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 短链接分组接口实现层
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    private final RedissonClient redissonClient;

    @Value("${short-link.group.max-num}")
    private Integer maxNum;

    private final ShortLinkClient shortLinkClient;

    @Override
    public void saveGroup(String groupName) {
        String username = UserContext.getUsername();
        RLock lock = redissonClient.getLock(RedisCacheConstant.LOCK_GROUP_CREATE_KEY);
        try {
            lock.lock();
            List<GroupDO> groupList = lambdaQuery()
                    .eq(GroupDO::getUsername, username)
                    .eq(GroupDO::getDelFlag, 0)
                    .list();
            if (CollUtil.isNotEmpty(groupList) && groupList.size() == maxNum) {
                throw new ClientException(String.format("已超出最大分组数：%d", maxNum));
            }
        } finally {
            lock.unlock();
        }
        saveGroup(username, groupName);
    }

    @Override
    public void saveGroup(String username, String groupName) {
        String gid;
        do {
            gid = RandomGenerator.generateFixLenRandomString();
        } while (hasGid(username, gid));
        GroupDO groupDO = GroupDO.builder()
                .gid(gid)
                .sortOrder(0)
                .username(username)
                .name(groupName)
                .build();
        save(groupDO);
    }

    /**
     * 判断gid是否已存在
     *
     * @param gid gid
     * @return true: 已存在 false: 不存在
     */
    private boolean hasGid(String username, String gid) {
        GroupDO groupDO = lambdaQuery()
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, Optional.ofNullable(username).orElse(UserContext.getUsername()))
                .one();
        return groupDO != null;
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        List<GroupDO> list = lambdaQuery()
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder, GroupDO::getUpdateTime)
                .list();
        Result<List<ShortLinkGroupCountQueryRespDTO>> result = shortLinkClient
                .shortLinkCountOfGroup(list.stream().map(GroupDO::getGid).toList());
        List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOList = BeanUtil.copyToList(list, ShortLinkGroupRespDTO.class);
        shortLinkGroupRespDTOList.forEach(item -> {
            String gid = item.getGid();
            Optional<ShortLinkGroupCountQueryRespDTO> first = result.getData().stream()
                    .filter(item1 -> item1.getGid().equals(gid))
                    .findFirst();
            first.ifPresent(each -> item.setShortLinkCount(each.getShortLinkCount()));
        });
        return shortLinkGroupRespDTOList;
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        lambdaUpdate()
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, requestParam.getGid())
                .eq(GroupDO::getDelFlag, 0)
                .update(BeanUtil.toBean(requestParam, GroupDO.class));
    }

    @Override
    public void deleteGroup(String gid) {
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(1);
        lambdaUpdate()
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0)
                .update(groupDO);
    }

    @Override
    public void sort(List<ShortLinkGroupSortReqDTO> requestParam) {
        requestParam.forEach(item -> {
            GroupDO groupDO = GroupDO.builder()
                    .sortOrder(item.getSortOrder())
                    .build();
            lambdaUpdate()
                    .eq(GroupDO::getGid, item.getGid())
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getDelFlag, 0)
                    .update(groupDO);
        });
    }
}




